<?php declare(strict_types = 1);

namespace Gnway\Ticket\Rest\Util;

use Gnway\Ticket\Rest\Contracts\HttpResponseInterface;
use Gnway\Ticket\Rest\Response\JsonTemplate;

final class ResponseUtils
{

  /**
   * Don't let anyone instantiate this class
   */
  private function __construct() {}

  /**
   * Api统一返回结果
   *
   * @param integer|array $status
   * @param string        $message
   * @param array         $result
   * @return array
   */
  public static function getJsonStruct($status, string $message = '', array $result = []): array
  {
    if (is_array($status)) {
      return $status;
    }

    return self::getJsonTemplate((int)$status, $message, $result)->toArray();
  }

  /**
   * Instantiate JsonTemplate
   *
   * @param int    $status
   * @param string $message
   * @param array  $result
   * @return JsonTemplate
   */
  public static function getJsonTemplate(int $status, string $message = '', array $result = []): JsonTemplate
  {
    return new JsonTemplate($status, $message, $result);
  }

  /**
   * Send Http Response
   *
   * @param HttpResponseInterface|null $response
   * @param bool                       $flushes
   * @return void
   */
  public static function send(?HttpResponseInterface $response, bool $flushes = TRUE): void
  {
    if ($response === NULL) {
      return;
    }

    //Send http header
    self::sendHeaders($response->getHttpResponseCode(), $response->getHttpResponseHeaders());

    self::write($response->getValue());

    $flushes && function_exists('fastcgi_finish_request') && fastcgi_finish_request();
  }

  /**
   * Send Http Headers
   *
   * @param int   $code
   * @param array $headers
   * @return void
   */
  public static function sendHeaders(int $code, array $headers): void
  {
    if (headers_sent() || empty($headers)) {
      return;
    }

    foreach ($headers as $header) {
      header($header, TRUE, $code);
    }
  }

  /**
   * Write buffer to client
   *
   * @param string $buffer
   * @return void
   */
  public static function write(string $buffer): void
  {
    echo $buffer;
  }

  /**
   * Write buffer to client
   *
   * @param string $buffer
   * @return void
   */
  public static function writeln(string $buffer): void
  {
    self::write($buffer . PHP_EOL);
  }

  /**
   * Forces any content in the buffer to be written to the client
   *
   * @return void
   */
  public static function flushBuffer(): void
  {
    ob_flush();
    flush();
  }
}